var that=this;
$(function(){
    //创建dom元素
    $('body').append('<input id="X-Idempotent-Token" type="hidden" th:value="${X-Idempotent-Token}"/>');
    $(document).ajaxSend(function(event, jqxhr, settings) {
        jqxhr.setRequestHeader("X-Idempotent-Token", that.token());
    });
    $(document).ajaxComplete(function(event, jqxhr, settings){
        const res = jqxhr.responseText;
        let respMessage = res;
        if(that.isJson(respMessage)){
            const json = JSON.parse(respMessage);
            if(json.hasOwnProperty("msg")){
                respMessage=json["msg"];
            }else{
                if(json.hasOwnProperty("code")){
                    const code = json["code"];
                    if(code=='1521'){
                        respMessage=json["message"];
                    }
                }
            }
        }

        //alert("AJAX 请求完成，响应数据："+respMessage);
        if(respMessage!='请勿重复提交'&&!respMessage.startsWith("X-Idempotent-Token-")){
            that.refreshToken();
        }
        if(respMessage=='请勿重复提交'){
            layer.msg(respMessage);
            jqxhr.abort();
            event.stopPropagation();
        }
        // alert("AJAX 请求完成，响应数据："+res);
    });
});

/**
 * 判断是否json
 * @param $string
 * @returns {boolean}
 */
function isJson($string)
{
    try {
        if(typeof JSON.parse($string) == 'object')
            return true;
        return false;
    } catch (e) {
        console.log(e);
        return false;
    }
}

//刷新页面token
var refreshToken = function () {
    $.get("/token", function (data) {
        if (data != null) {
            console.log("getToken():" + data);
            $("#X-Idempotent-Token").val(data);
        }
    });
};
//获取页面token
var token=function(){
    const data = $("#X-Idempotent-Token").val();
    console.log("token():"+data);
    return data;
}